<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/5/15
 * Time: 13:52
 * 点赞
 */
require_once dirname(__DIR__) . "/common.php";

use app\cls\tom\Response;
use app\cls\tom\Praise;
use app\cls\tom\SysResource;
use app\cls\tom\Queue;
use app\cls\tom\Tools;

$referer = isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:"";
//if(empty($referer)){
//    Response::badRequest();
//}
//$host = @parse_url($referer,PHP_URL_HOST);
//if(!in_array($host,["localhost"])){
//    Response::badRequest();
//}
if(empty($_POST["click_info"])){
    Response::output(-1,"参数错误");
}
$clickInfo = @json_decode($_POST["click_info"],true);
if(empty($clickInfo)){
    Response::output(-1,"数据格式错误");
}
if(!is_array($clickInfo)){
    Response::output(-1,"数据格式错误");
}
foreach($clickInfo as $info){
    if(empty($info["num"]) || empty($info["id"])){
        Response::output(-1,"数据格式错误");
    }
}

$token = empty($_SERVER["HTTP_AUTH_TOKEN"]) ? NULL : $_SERVER["HTTP_AUTH_TOKEN"];
$userInfo = [];
if(!empty($token)){
    $userService = new \app\service\User();
    $info = $userService->validateToken($token,false);
    if(!($info instanceof Response)){
        $userInfo = $info;
    }
}
$re = [];
$queueData = [];
$redis = SysResource::getRedis();
$queueObj = new Queue($redis,REDIS_PREFIX."praise");

$praiseObj = new Praise($userInfo ? $userInfo["user_uuid"] : "","",SysResource::getRedis(),"video");
$dyKeyPrefix = REDIS_PREFIX."video_dy_";
try{
    foreach($clickInfo as $info){
        if(is_array($info)){
            $id = $info["id"];
            if($id && Tools::isLegalUUID($id)){
                //1.点赞
                $praiseObj->setIdentity($id);
                $num = $praiseObj->clickPraise($info["num"],true);
                $re[$info["id"]] = $num;
                $queueData[] = ["id"=>$id,"num"=>$info["num"],"user_uuid"=>$userInfo ? $userInfo["user_uuid"] : ""];
                //2.存储动态
                if(!empty($userInfo)){
                    $dyKey = $dyKeyPrefix.$id;
                    $redis->zAdd($dyKey,intval(microtime(true)*1000),$userInfo["user_uuid"]);
                    //动态截断
                    $redis->zRemRangeByRank($dyKey,10,-1);
                }
            }
        }
    }
    $queueObj->push(json_encode($queueData),rand(1,100));
    Response::output(0,"点赞成功",$re);
}catch (Exception $e){
    Response::output(-1,"失败");
}


